package net.pws.oos.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.pws.common.jackson.JsonUtils;
import net.pws.common.persistence.EntityManager;
import net.pws.common.util.StringUtils;
import net.pws.oos.biz.model.Dict;
import net.pws.oos.biz.model.IndicatorTemplate;
import net.pws.oos.biz.query.DictFinder;
import net.pws.oos.biz.query.IndicatorFinder;
import net.pws.oos.biz.query.IndicatorTemplateFinder;
import net.pws.oos.biz.query.parameter.IndicatorTemplateQueryParameter;
import net.pws.oos.biz.service.IndicatorTemplateService;
import net.pws.oos.security.SecurityUtils;
import net.pws.oos.web.dto.IndicatorTemplateDto;
import net.pws.oos.web.dto.IndicatorTemplateTreeNodeDto;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 模板管理
 */
@Controller
@RequestMapping("/biz/template")
@SuppressWarnings({ "rawtypes", "unchecked" })
public class IndicatorTemplateAction {
    
    public final transient Log logger = LogFactory.getLog(IndicatorTemplateAction.class);
    
    @Autowired
    private IndicatorTemplateService indicatorTemplateService;
    
    @Autowired
    private IndicatorTemplateFinder indicatorTemplateFinder;
    
    @Autowired
    private DictFinder dictFinder;
    
    @Autowired
    private EntityManager entityManager;
    
    @Autowired
    private IndicatorFinder indicatorFinder;
    
    @RequestMapping("/count.json")
    @ResponseBody
    public Object getIndicatorTemplateCount(IndicatorTemplateQueryParameter queryParams) {
        queryParams = initOrganParameterByRole(queryParams);
        Map map = new HashMap();
        try {
            map.put("data", indicatorTemplateFinder.countIndicatorTemplate(queryParams));
            map.put("succeed", Boolean.TRUE);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
        
        return map;
    }
    
    
    @RequestMapping("/list.json")
    @ResponseBody
    public Object getIndicatorTemplateList(IndicatorTemplateQueryParameter queryParams) {
        queryParams = initOrganParameterByRole(queryParams);
        Map map = new HashMap();
        try {
            List<Map> indicatorTemplates = indicatorTemplateFinder.getIndicatorTemplateMapList(queryParams,
                                                                                queryParams.getStart(),
                                                                                queryParams.getLimit());
            
            map.put("data", indicatorTemplates);
            map.put("succeed", Boolean.TRUE);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
        return map;
    }
    
    private IndicatorTemplateQueryParameter initOrganParameterByRole(IndicatorTemplateQueryParameter queryParams) {
        if (queryParams == null) {
            queryParams = new IndicatorTemplateQueryParameter();
        }
        if (StringUtils.isEmpty(queryParams.getAncestorId())) {
            queryParams.setAncestorId(SecurityUtils.currentUser().getOrganId());
        }
        
        return queryParams;
    }
    
    @RequestMapping("/detail.do")
    public String detailPage(String id, ModelMap map) {
    	map.put("specials", dictFinder.listDicts(Dict.SPECIAL));
    	map.put("data", IndicatorTemplateDto.from(indicatorTemplateFinder.getIndicatorTemplateMap(id)));
    	return "template/detail";
    }
    
    @RequestMapping("/edit.do")
    public String prepareEditIndicatorTemplate(String id, ModelMap map) {
        map.put("specials", dictFinder.listDicts(Dict.SPECIAL));
        map.put("constructionModels", indicatorFinder.getIndicatorValueListByIndicatorProp("constructionModel"));
        if (StringUtils.isEmpty(id)) {
            return "template/new";
        }
        map.put("data",
                IndicatorTemplateDto.from(indicatorTemplateFinder.getIndicatorTemplateMap(id)));
        return "template/edit";
    }
    
    @RequestMapping("/save.json")
    @ResponseBody
    public Object saveIndicatorTemplate(IndicatorTemplateDto dto) {
        Map map = new HashMap();
        try {
            map.put("data",
                    IndicatorTemplateDto.from(indicatorTemplateService.saveIndicatorTemplate(IndicatorTemplateDto.to(dto, entityManager))));
            map.put("succeed", Boolean.TRUE);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
        return map;
    }
    
    @RequestMapping("/delete.json")
    @ResponseBody
    public Object removeIndicatorTemplate(String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                throw new IllegalArgumentException("指标项ID为空！");
            }
            
            IndicatorTemplate organ = entityManager.find(IndicatorTemplate.class, id);
            if (null == organ) {
                return JsonUtils.succeedMap(null);
            }
            
            indicatorTemplateService.deleteIndicatorTemplate(id);
            return JsonUtils.succeedMap(null);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    

    
    @RequestMapping("/detail/tree.json")
    @ResponseBody
    public Object getTemplateDetailList(String id,
                                      String templateId,
                                      HttpServletRequest request) {
        try {
        	List<Map> indicators = null;
            if (StringUtils.isNotEmpty(templateId)) {
            	indicators = indicatorTemplateFinder.getIndicatorTemplateTreeNode(id, templateId);
            }
            
            List<IndicatorTemplateTreeNodeDto> indicatorDtos = new ArrayList<IndicatorTemplateTreeNodeDto>();
            for (Map menu : indicators) {
            	indicatorDtos.add(IndicatorTemplateTreeNodeDto.from(menu, request));
            }
            
            return JsonUtils.succeedMap(indicatorDtos);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    @RequestMapping("/detail/save.json")
    @ResponseBody
    public Object saveTemplateDetail(String templateId, String data) {
        try {
        	List<Map> templateDetail = JsonUtils.parseList(data);
			templateDetail = indicatorTemplateService.saveTemplateDetail(
					templateId, templateDetail);
            
            return JsonUtils.succeedMap(templateDetail);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/query.do")
    public String queryPage(ModelMap map) {
        map.put("specials", dictFinder.listDicts(Dict.SPECIAL));
        
        return "template/query";
    }
}
